<template>
  <a-card>
    <br />
    <!--表单 -->
    <a-form-model v-bind="layout" :model="form" :rules="rules" ref="ruleForm">
      <a-row>
        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item label="单据号" ref="document" prop="document">
            <a-select
              v-model="form.document"
              style="width: 100%"
              showSearch
              @change="getformlist"
              @search="searchdocNoList"
            >
              <a-select-option
                v-for="item in docNoList"
                :key="item"
                :value="item"
                >{{ item }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item label="仓库名称" ref="storname" prop="storname">
            <a-select
              disabled
              v-model="form.storname"
              showSearch
              style="width: 100%"
              @change="setdataSourcestorageUnit"
            >
              <a-select-option
                v-for="item in storageList"
                :key="item.warehouseId"
                :value="
                  item.warehouseNo +
                  '|' +
                  item.storname +
                  '|' +
                  item.warehouseId
                "
              >
                {{ item.warehouseNo }}
                {{ item.storname }}
              </a-select-option></a-select
            >
          </a-form-model-item>
        </a-col>
        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item
            label="盘点日期"
            ref="inventoryDate"
            prop="inventoryDate"
          >
            <a-date-picker
              v-model="form.inventoryDate"
              disabled
            ></a-date-picker>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row> </a-row>
      <a-row>
        <a-col align="right">
          <a-button type="primary" @click="getSearch"> 查询 </a-button>
          <a-button :style="{ marginLeft: '8px' }" @click="Reset">
            重置
          </a-button>
        </a-col>
      </a-row>
    </a-form-model>
    <!-- 表格 -->
    <br />
    <br />
    <br />
    <a-table
      v-cloak
      :columns="columns"
      style="margin-top: 20px"
      :scroll="{ x: 1000, y: 670 }"
      :data-source="dataSource"
    >
      <template slot="序号" slot-scope="text, record">
        <editable-cell
          :text="text"
          @change="onCellChange(record.key, 'key', $event)"
        />
      </template>
      <span slot="inventoryQuantity" slot-scope="text, record">
        <a-input-number
          :precision="3"
          :min="0"
          @change="changenumber(text, record)"
          v-model="record.inventoryQuantity"
        />
      </span>
      <span slot="differencesQuantity" slot-scope="text, record">
        <a-input-number
          :precision="3"
          disabled
          v-model="record.differencesQuantity"
        />
      </span>
    </a-table>
    <a-form-model v-bind="layout" :model="form" :rules="rules" ref="ruleForm">
      <a-row>
        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item label="盘点人" ref="checkers" prop="checkers">
            <a-select
              disabled
              v-model="form.checkers"
              @change="getcwhsmanagerId"
              showSearch
              style="width: 100%"
              @search="searchUserInfoList"
            >
              <a-select-option
                v-for="item in UserList"
                :key="item.id"
                :value="item.workNo + '|' + item.username + '|' + item.id"
              >
                {{ item.workNo }} {{ item.username }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item label="监盘人" ref="supervisor" prop="supervisor">
            <a-select
              @change="getsupervisorId"
              disabled
              v-model="form.supervisor"
              showSearch
              styple="width:100%"
              @search="searchUserInfoList"
            >
              <a-select-option
                v-for="item in UserList"
                :key="item.id"
                :value="item.workNo + '|' + item.username + '|' + item.id"
              >
                {{ item.workNo }} {{ item.username }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item label="审计人" ref="auditor" prop="auditor">
            <a-select
              v-model="form.auditor"
              disabled
              @change="getauditorId"
              showSearch
              style="width: 100%"
              @search="searchUserInfoList"
            >
              <a-select-option
                v-for="item in UserList"
                :key="item.id"
                :value="item.workNo + '|' + item.username + '|' + item.id"
              >
                {{ item.workNo }} {{ item.username }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item label="制单人">
            <a-input v-model="form.documentmaker" disabled></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item
            label="制单时间"
            ref="documenttime"
            prop="documenttime"
          >
            <a-date-picker v-model="form.documenttime" disabled>
            </a-date-picker>
          </a-form-model-item>
        </a-col>
        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24"> </a-col>
      </a-row>
      <a-row>
        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24"> </a-col>
        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-button style="margin-right: 20px" @click="update" type="primary"
            >更新</a-button
          >
          <a-button @click="exportToExcel">导出</a-button>
        </a-col>
        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24"> </a-col>
      </a-row>
    </a-form-model>
  </a-card>
</template>
<script>
import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax(); // 公用接口
// 引入
import moment from "moment";
import "moment/locale/zh-cn";
import { PanDianChaXunHttp } from "../../services/modules/pandian/pandianchaxun";
const $http = new PanDianChaXunHttp();
//导出
import FileSaver from "file-saver";
import XLSX from "xlsx";
import { sheet2blob } from "@/utils/export.js";
const columns = [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    align: "center",
  },
  {
    title: "仓库名称",
    dataIndex: "storname",
    key: "storname",
    align: "center",
  },
  {
    title: "仓位",
    dataIndex: "position",
    key: "position",
    align: "center",
  },
  {
    title: "存货编码",
    dataIndex: "invcode",
    key: "invcode",
    align: "center",
  },
  {
    title: "存货名称",
    dataIndex: "invname",
    key: "invname",
    align: "center",
  },
  {
    title: "规格型号",
    dataIndex: "invspec",
    key: "invspec",
    align: "center",
  },
  {
    title: "单位",
    dataIndex: "measname",
    key: "measname",
    align: "center",
  },
  {
    title: "批次号",
    dataIndex: "batchNumber",
    key: "batchNumber",
    align: "center",
  },
  {
    title: "账面数量",
    dataIndex: "bookQuantity",
    key: "bookQuantity",
    align: "center",
  },
  {
    title: "盘点数量",
    dataIndex: "inventoryQuantity",
    key: "inventoryQuantity",
    align: "center",
    scopedSlots: { customRender: "inventoryQuantity" },
  },
  {
    title: "差异数量",
    dataIndex: "differencesQuantity",
    key: "differencesQuantity",
    align: "center",
    scopedSlots: { customRender: "differencesQuantity" },
  },
];
export default {
  data() {
    return {
      queryParam: {
        //查询参数
        page: 1, //第几页
        size: 10, //每页中显示数据的条数
        hosName: "",
        hosCode: "",
        province: "",
        city: "",
      },
      //===============分页========================
      pagination: {
        total: 0,
        current: 1,
        pageSize: this.maxSize, //每页中显示10条数据
        pageSizeOptions: ["10"], //每页中显示的数据
        showTotal: (total) => `共有${total}条数据`, //分页中显示总的数据
        showSizeChanger: true, // 显示页面条数改变
        showQuickJumper: true, // 显示快速跳转
      },
      form: {
        document: "", //单据号
        storname: "", //仓库名称
        warehouseId: "", //仓库id
        warehouseNo: "", //仓库编码
        inventoryDate: moment().format("YYYY-MM-DD"), //盘点日期
        checkers: "", //盘点人
        checkersId: "", //盘点人id
        checkersNo: "", //盘点人编码
        supervisor: "", //监盘人
        supervisorId: "", //监盘人id
        supervisorNo: "", //监盘人编码
        auditor: "", //审计人
        auditorId: "", //审计人id
        auditorNo: "", //审计人编码
        documentmaker: this.$store.state.user.info.username, //制单人
        documentmakerId: this.$store.state.user.info.id, //制单人id
        documenttime: moment().format("YYYY-MM-DD"), //制单时间
      },
      columns,
      storageList: [], // 仓库列表
      docNoList: [], //单据号列表
      UserList: [], // 盘点人列表
      workNoList: [], // 判重使用
      // 表格数据
      dataSource: [],
      maxSize: "",
      // 搜索栏布局
      layout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 15 },
      },
      rules: {
        document: [
          {
            required: true,
            message: "单据号为必填项！",
            trigger: "blur",
          },
        ],
        storname: [
          {
            required: true,
            message: "仓库名称为必填项！",
            trigger: "blur",
          },
        ],
        inventoryDate: [
          {
            required: true,
            message: "盘点日期为必填项！",
            trigger: "change",
          },
        ],
        checkers: [
          {
            required: true,
            message: "盘点人为必填项！",
            trigger: "blur",
          },
        ],
        supervisor: [
          {
            required: true,
            message: "监盘人为必填项！",
            trigger: "blur",
          },
        ],
        auditor: [
          {
            required: true,
            message: "审计人为必填项！",
            trigger: "blur",
          },
        ],
        documenttime: [
          {
            required: true,
            message: "制单时间为必填项！",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    //根据单据号渲染表单
    getformlist(data) {
      $http.getinventorylist("?documentNo=" + data).then((res) => {
        this.form.documentmaker = res.result.records[0].producerUser_dictText; //制单人
        this.form.checkers = res.result.records[0].inventoryUser_dictText; //盘点人
        this.form.auditor = res.result.records[0].auditorUser_dictText; //审计人
        this.form.inventoryDate = res.result.records[0].inventoryDate; //盘点日期
        this.form.storname = res.result.records[0].storname; //仓库名称
        this.form.documenttime = res.result.records[0].producerDate; //制单时间
        this.form.supervisor = res.result.records[0].supervisorUser_dictText; //监盘人
      });
    },
    //查询单据号
    searchdocNoList(value) {
      if (value != "") {
        let queryPath = "?documentNo=" + value;
        $http.getDocumentNoList(queryPath).then((res) => {
          console.log("queryPath", queryPath);
          // let data=res.result;
          this.docNoList = res.result;
          this.docNoList = Array.from(new Set(this.docNoList));
          console.log(this.docNoList);
        });
      }
      console.log("docNoList", this.docNoList);
    },
    //更新
    update() {
      this.$refs.ruleForm.validate(() => {
        let array = [];
        for (let i = 0; i < this.dataSource.length; i++) {
          let data = {
            auditorUser: this.dataSource[i].auditorUser,
            batchNumber: this.dataSource[i].batchNumber,
            bookQuantity: this.dataSource[i].bookQuantity,
            differencesQuantity: this.dataSource[i].differencesQuantity,
            inventoryDate: this.dataSource[i].inventoryDate,
            inventoryQuantity: this.dataSource[i].inventoryQuantity,
            inventoryUser: this.dataSource[i].inventoryUser,
            pkInvbasdoc: this.dataSource[i].pkInvbasdoc, //存货档案主键
            pkStordoc: this.dataSource[i].pkStordoc, //仓库档案主键
            position: this.dataSource[i].position,
            producerDate: this.dataSource.producerDate,
            producerUser: this.dataSource[i].producerUser,
            supervisorUser: this.dataSource[i].supervisorUser,
            id: this.dataSource[i].id,
          };
          array.push(data);
          // console.log(data, "1111111111111");

          console.log("supervisorId", this.form.supervisorId);
        }
        console.log("array", array);
        if (this.form.document !== "") {
          $http.updateinventorylist(array).then((res) => {
            console.log(res);
            this.$message.success("更新成功");
          });
        } else {
          this.$message.error("更新失败");
        }
      });
    },
    //导出
    exportToExcel() {
      $http
        .getinventorylist(
          "?pageNo=1&pageSize=" +
            this.maxSize +
            "&pkStordoc=" +
            this.form.warehouseId
        )
        .then((res) => {
          console.log("导入的数据", res.result.records);
          let array = res.result.records;
          this.exportBasic(array);
        });
    },
    // 接收数组，进行导出
    exportBasic(Array) {
      console.log("要导出的数据为:::::", Array);
      // 规整要导出的数据:::::
      let array = [];
      for (let i = 0; i < Array.length; i++) {
        let data = {
          序号: i + 1,
          仓库名称: Array[i].storname,
          仓位: Array[i].position,
          存货编码: Array[i].invcode,
          存货名称: Array[i].invname,
          规格型号: Array[i].invspec,
          单位: Array[i].measname,
          批次号: Array[i].batchNumber,
          账面数量: Array[i].bookQuantity,
          盘点数量: this.dataSource[i].inventoryQuantity,
          差异数量: this.dataSource[i].differencesQuantity,
        };
        array.push(data);
      }
      // 生成 sheet 表格 数据
      let sheet = XLSX.utils.json_to_sheet(array, {
        // 对导出内容进行相应的排序,手动排序。
        header: [
          "序号",
          "仓库名称",
          "仓位",
          "存货编码",
          "存货名称",
          "规格型号",
          "单位",
          "批次号",
          "账面数量",
          "盘点数量",
          "差异数量",
        ],
      });
      // 生成导出表格
      let blob = sheet2blob(sheet);
      try {
        FileSaver.saveAs(
          new Blob([blob], {
            type: "application/octet-stream",
          }),
          "盘点查询档案.xlsx" // 导出文件夹名称
        );
      } catch (e) {
        console.log(e);
      }
    },
    //计算差异数量
    changenumber(text, record) {
      console.log(record, "?2");
      record.differencesQuantity = this.$set(
        record,
        "differencesQuantity",
        record.inventoryQuantity - record.bookQuantity
      );

      console.log(record.differencesQuantity);
      console.log(record, "11111111");
    },
    //搜索开始
    getSearch() {
      if (this.form.document !== "") {
        $http
          .getinventorylist("?documentNo=" + this.form.document)
          .then((res) => {
            this.maxSize = res.result.total;
            this.showsearch();
          });
      } else {
        this.$message.error("单据号不能为空");
        console.log("提示单据号不能为空！");
      }
    },
    //
    showsearch() {
      $http
        .getinventorylist(
          "?documentNo=" +
            this.form.document +
            "&pageNo=1&pageSize=" +
            this.maxSize
        )
        .then((res) => {
          const pagination = { ...this.pagination }; //分页
          pagination.total = res.result.total; //分页
          pagination.pageSize = res.result.pageSize; //分页
          this.pagination = pagination; //分页

          this.dataSource = res.result.records;
          for (let i = 0; i < res.result.records.length; i++) {
            this.dataSource[i].key = (pagination.current - 1) * 10 + i + 1;
          }
          this.dataSoure.differencesQuantity =
            res.result.records.differencesQuantity;
          console.log(this.dataSource);
          console.log(this.form.warehouseId);
          console.log(res.result.list.length);
        });
    },
    //重置
    Reset() {
      this.form = {
        document: "", //单据号
        storname: "", //仓库名称
        inventoryDate: "", //盘点日期
        documenttime: "", //制单时间
        documentmaker: "", //制单人
        documentmakerId: "", //制单人id
      };
      this.dataSource = [];
      this.pagination = {
        page: 1,
        total: 0,
        current: 1,
        pageSize: 10, //每页中显示10条数据
        // showSizeChanger: true,
        pageSizeOptions: ["10"], //每页中显示的数据
        showTotal: (total) => `共有${total}条数据`, //分页中显示总的数据
      };
      // this.getinventorylist();
    },
    // ==============分页======================
    handleTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.queryParam.page = pagination.current;
      this.queryParam.size = pagination.pageSize;
      this.getinventorylist();
    },
    //获取列表
    getinventorylist() {
      let dd = this.queryParam.page; //分页
      console.log("dd", dd);
      (this.dataSource = []),
        $http.getinventorylist("?pageNo=" + dd).then((res) => {
          const pagination = { ...this.pagination }; //分页
          pagination.total = res.result.total; //分页
          pagination.pageSize = res.result.size; //分页
          this.pagination = pagination; //分页
          console.log("res----->", res);
          this.dataSource = res.result.records;
          let wowo = res.result.records;
          for (let i = 0; i < wowo.length; i++) {
            this.dataSource[i].key = (res.result.current - 1) * 10 + i + 1;
          }
        });
    },
    // 获取单号
    // getApplyOrder() {
    //   let queryPath = "?string=SCIN-";
    //   comHttp.getOrder(queryPath).then((res) => {
    //     this.form.document = res.message;
    //   });
    // },
    // 查询人员信息列表
    searchUserInfoList(value) {
      if (value != "") {
        let queryPath = "?username=" + value;
        comHttp.getUserInfoByUserName(queryPath).then((res) => {
          console.log("queryPath", this.queryPath);
          for (let i = 0; i < res.result.list.length; i++) {
            if (!this.workNoList.includes(res.result.list[i].workNo)) {
              let data = {
                username: res.result.list[i].username,
                id: res.result.list[i].id,
                workNo: res.result.list[i].workNo,
              };
              this.UserList.push(data);
              this.workNoList.push(res.result.list[i].workNo);
            }
          }
          console.log("userlist", this.UserList);
        });
      }
    },
    // 获取仓库
    getApplyStorage() {
      this.storageList = [];
      // 获取仓库名称
      comHttp.getStorageName().then((res) => {
        console.log("获取所有仓库", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            storname: res.result[i].storname, //仓库名称
            warehouseNo: res.result[i].storcode, //仓库编码
            warehouseId: res.result[i].pkStordoc, //id
          };
          this.storageList.push(data);
        }
        console.log("this.storageList", this.storageList);
      });
    },
    // 盘点人列表
    getcwhsmanagerId(data) {
      let array = data.split("|");
      this.form.checkersNo = array[0];
      this.form.checkers = array[1];
      this.form.checkersId = array[2];
      console.log(" this.searchForm", this.searchForm);
    },
    // 监盘人列表
    getsupervisorId(data) {
      let array = data.split("|");
      this.form.supervisorNo = array[0];
      this.form.supervisor = array[1];
      this.form.supervisorId = array[2];
      console.log(" this.searchForm", this.searchForm);
    },
    // 审计人列表
    getauditorId(data) {
      let array = data.split("|");
      this.form.auditorNo = array[0];
      this.form.auditor = array[1];
      this.form.auditorId = array[2];
      console.log(" this.searchForm", this.searchForm);
    },
    // 设置仓库名称, 上面表单触发事件
    setdataSourcestorageUnit(value) {
      let array = value.split("|");
      this.form.warehouseId = array[2];
      this.form.storname = array[1];
      this.form.warehouseNo = array[0];
    },
  },
  mounted() {
    this.getApplyStorage(); // 获取仓库
    // 获取单据号
    // this.getApplyOrder();
    //获取列表
    // this.getinventorylist();
  },
};
</script>
<style></style>
